import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Tabs, Tag, Popconfirm } from 'antd';
import { PlusOutlined, EyeOutlined, StopOutlined } from '@ant-design/icons';
import { ProcessInstanceApi, ProcessInstanceVO } from '../../../api/bpm/processInstance';

const { TabPane } = Tabs;
const { TextArea } = Input;

const BPMProcessInstance: React.FC = () => {
  const [myInstances, setMyInstances] = useState<ProcessInstanceVO[]>([]);
  const [managerInstances, setManagerInstances] = useState<ProcessInstanceVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('my');
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [cancelModalVisible, setCancelModalVisible] = useState(false);
  const [currentInstance, setCurrentInstance] = useState<ProcessInstanceVO | null>(null);
  const [form] = Form.useForm();
  const [cancelForm] = Form.useForm();

  // 获取我的流程实例
  const fetchMyInstances = async () => {
    setLoading(true);
    try {
      const response = await ProcessInstanceApi.getProcessInstanceMyPage({});
      setMyInstances(response.data?.list || []);
    } catch (error) {
      message.error('获取我的流程实例失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取管理流程实例
  const fetchManagerInstances = async () => {
    setLoading(true);
    try {
      const response = await ProcessInstanceApi.getProcessInstanceManagerPage({});
      setManagerInstances(response.data?.list || []);
    } catch (error) {
      message.error('获取管理流程实例失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'my') {
      fetchMyInstances();
    } else if (activeTab === 'manager') {
      fetchManagerInstances();
    }
  }, [activeTab]);

  // 创建流程实例
  const handleCreate = async (values: any) => {
    try {
      await ProcessInstanceApi.createProcessInstance(values);
      message.success('创建流程实例成功');
      setCreateModalVisible(false);
      form.resetFields();
      fetchMyInstances();
    } catch (error) {
      message.error('创建流程实例失败');
    }
  };

  // 取消流程实例
  const handleCancel = async (values: any) => {
    if (!currentInstance) return;
    
    try {
      if (activeTab === 'my') {
        await ProcessInstanceApi.cancelProcessInstanceByStartUser(currentInstance.id, values.reason);
      } else {
        await ProcessInstanceApi.cancelProcessInstanceByAdmin(currentInstance.id, values.reason);
      }
      message.success('取消流程实例成功');
      setCancelModalVisible(false);
      setCurrentInstance(null);
      cancelForm.resetFields();
      if (activeTab === 'my') {
        fetchMyInstances();
      } else {
        fetchManagerInstances();
      }
    } catch (error) {
      message.error('取消流程实例失败');
    }
  };

  // 打开取消模态框
  const openCancelModal = (instance: ProcessInstanceVO) => {
    setCurrentInstance(instance);
    setCancelModalVisible(true);
  };

  const getStatusTag = (status: number) => {
    const statusMap: Record<number, { color: string; text: string }> = {
      1: { color: 'processing', text: '进行中' },
      2: { color: 'success', text: '已完成' },
      3: { color: 'error', text: '已取消' },
      4: { color: 'warning', text: '已暂停' }
    };
    const statusInfo = statusMap[status] || { color: 'default', text: '未知' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  const columns = [
    {
      title: '流程名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '业务键',
      dataIndex: 'businessKey',
      key: 'businessKey',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ProcessInstanceVO) => (
        <Space size="middle">
          <Button
            type="default"
            icon={<EyeOutlined />}
          >
            查看
          </Button>
          {record.status === 1 && (
            <Button
              type="default"
              danger
              icon={<StopOutlined />}
              onClick={() => openCancelModal(record)}
            >
              取消
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const getCurrentData = () => {
    return activeTab === 'my' ? myInstances : managerInstances;
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setCreateModalVisible(true)}
        >
          发起流程
        </Button>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="我的流程" key="my" />
        <TabPane tab="管理流程" key="manager" />
      </Tabs>

      <Table
        columns={columns}
        dataSource={getCurrentData()}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      {/* 创建流程实例模态框 */}
      <Modal
        title="发起流程"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Form.Item
            name="processDefinitionKey"
            label="流程定义"
            rules={[{ required: true, message: '请输入流程定义Key' }]}
          >
            <Input placeholder="请输入流程定义Key" />
          </Form.Item>
          <Form.Item
            name="businessKey"
            label="业务键"
          >
            <Input placeholder="请输入业务键" />
          </Form.Item>
          <Form.Item
            name="variables"
            label="流程变量"
          >
            <TextArea placeholder="请输入流程变量（JSON格式）" rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 取消流程实例模态框 */}
      <Modal
        title="取消流程"
        open={cancelModalVisible}
        onCancel={() => {
          setCancelModalVisible(false);
          setCurrentInstance(null);
          cancelForm.resetFields();
        }}
        onOk={() => cancelForm.submit()}
        destroyOnClose
      >
        <Form
          form={cancelForm}
          layout="vertical"
          onFinish={handleCancel}
        >
          <Form.Item
            name="reason"
            label="取消原因"
            rules={[{ required: true, message: '请输入取消原因' }]}
          >
            <TextArea placeholder="请输入取消原因" rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BPMProcessInstance;